﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PrepareContract.aspx.cs" Inherits="CRMWeb.Pages.Application.PrepareContract" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>

    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/icon.css" />
    <link rel="stylesheet" type="text/css" href="/Css/CrmStyle.css" />
    <script type="text/javascript" src="/Scripts/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/EasyUI/jquery.easyui.min.js"></script>
    <script src="../../Scripts/jquery.formatCurrency-1.4.0.js"></script>
    <script src="../../Scripts/jquery.formatCurrency.all.js"></script>
    <script src="../../Scripts/jquery.maskedinput.js"></script>
    <script src="../../Scripts/jquery.maskedinput.min.js"></script>
    <style type="text/css">
        .lable_left
        {
            text-align: left;
            width: 120px;
            margin-left: 10px;
        }

        .no_border
        {
            height: 350px;
            padding: 10px;
            width: 95%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div class="easyui-panel" id="pnlMain" style="width: auto; height: auto" title="New Loan Contract">
            <input type="hidden" id="hdnUserName" runat="server" />
            <div id="divcontrols" class="no_border" data-options="region:'center',split:true,border:false">
                <div class="equal_div" style="width: 50%; height: auto; margin-left: 5%;">
                    <div class="fitem">
                        <label style="width: 160px">Loan Amount :</label>
                        <input id="txtLoanAmount" oninput="changePrice('txtLoanAmount');" onchange="IsValidLoanAmount()" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label id="lblTerm" style="width: 160px">Loan Term  :</label>
                        <input id="txtTerm" class="easyui-numberbox" onblur="CheckPaymentTermsByMonth()" type="text" data-options="min:1,max:52" style="width: 40px" />
                        <label id="LabelWeeks" style="width: 100px">Weeks</label>
                    </div>
                    <div class="fitem">
                        <label style="width: 160px"></label>
                        <input id="lblTermByMonth" class="easyui-validatebox" type="text" style="background-color: LightGray; width: 40px;" readonly="yes" />
                        <label id="labelMonths" style="width: 100px">Months</label>
                    </div>
                    <div class="fitem">
                        <label style="width: 160px">Establishment Fee :</label>
                        <input id="txtEstablishFee" style="width: 120px" readonly="yes" />
                        %
                    </div>
                    <div class="fitem">
                        <label style="width: 160px">Monthly Fee :</label>
                        <input id="txtMontlyFee" style="width: 120px" readonly="yes" />
                        %
                    </div>
                    <div class="fitem">
                        <label style="width: 160px">schedule Settle Date :</label>
                        <input id="txtSettleDate" class="easyui-datebox" data-options="formatter:au_formatter,parser:au_parser" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label style="width: 160px">1st Payment Date :</label>
                        <input id="txtFirstPaymentDate" class="easyui-datebox" data-options="formatter:au_formatter,parser:au_parser" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label style="width: 160px">Repayment Frequency :</label>
                        <select id="cmbRepaymentBy" onchange="CheckPaymentTermsByMonth()">
                            <%--onchange="InvalidDateHandler"--%>
                            <option value="7">Weekly</option>
                            <option value="14">Fortnightly</option>
                            <option value="30">Monthly</option>
                        </select>
                    </div>
                    <div class="fitem">
                        <label style="width: 160px">Last Payment Date :</label>
                        <input id="txtLastPaymentDate" type="text" style="background-color: LightGray; width: 100px;" readonly="yes" />
                    </div>
                    <br />
                    <div class="fitem">
                        <label style="width: 160px"></label>
                        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-calculator" id="lbCalculate" onclick="Calculate_payment()">Calculator</a>
                    </div>
                    <div class="fitem">
                        <label id="lblmsg" style="color: red; width: auto;"></label>
                    </div>
                    <div class="fitem">
                        <label style="width: 160px">Repayment  :</label>
                        <input id="txtRepayment" oninput="changePrice('txtRepayment');" readonly="yes" type="text" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label style="width: 160px">Total Establishment Fee :</label>
                        <input id="txtTotalEstablishFee" oninput="changePrice('txtTotalEstablishFee');" readonly="yes" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label style="width: 160px">Total Monthly Fee :</label>
                        <input id="txtTotalMonthlyFee" oninput="changePrice('txtTotalMonthlyFee');" readonly="yes" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label style="width: 160px">Total Fee :</label>
                        <input id="txtTotalFee" readonly="yes" oninput="changePrice('txtTotalFee');" style="width: 120px" />
                    </div>
                    <br />
                    <div class="fitem">
                        <label style="width: 160px"></label>
                        <input id="hdnLoanContractID" type="hidden" />
                        <input id="hdnContactID" type="hidden" />
                        <input id="hdnFilePath" type="hidden" />

                        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" id="btnSchedule" onclick="PrepareSchedule()">Schedule </a>
                    </div>
                    <br />

                    <div class="fitem">
                        <label style="width: 160px">Draft Update Time : </label>
                        <label id="txtContractCreateDate" style="color: maroon; width: auto"></label>
                    </div>
                    <br />
                    <div class="fitem">
                        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" onclick="confirm()">Close </a>
                    </div>
                </div>
                <div class="equal_div" style="width: 40%; height: auto">

                    <div class="fitem">
                        <label class="lable_left">Client :</label>
                    </div>
                    <div class="fitem">
                        <label class="lable_left">First Name:</label>
                        <input id="txtFirstName" class="easyui-validatebox" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label class="lable_left">Middle Name:</label>
                        <input id="txtMiddleName" class="easyui-validatebox" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label class="lable_left">Last Name:</label>
                        <input id="txtLastName" class="easyui-validatebox" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label class="lable_left">DOB:</label>
                        <input id="txtDateBirth" class="easyui-datebox" data-options="formatter:au_formatter,parser:au_parser" style="width: 120px;" />
                    </div>
                    <div class="fitem">
                        <label class="lable_left">Driver Licence:</label>
                        <input id="txtDriverLicense" class="easyui-validatebox" style="width: 120px" />
                    </div>

                    <div class="fitem">
                        <label class="lable_left">Street:</label>
                        <input id="txtStreetNo" class="easyui-validatebox" style="width: 55px" />
                        <input id="txtStreet" class="easyui-validatebox" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label class="lable_left">Suburb:</label>
                        <input id="txtSuburb" class="easyui-validatebox" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label class="lable_left">State/ Postcode:</label>
                        <select id="cmbState" data-options="panelHeight:'auto'" style="width: 90px;" class="easyui-combobox">
                            <option value="">-Select-</option>
                            <option value="NSW">NSW</option>
                            <option value="QLD">QLD</option>
                            <option value="VIC">VIC</option>
                            <option value="SA">SA</option>
                            <option value="WA">WA</option>
                            <option value="TAS">TAS</option>
                            <option value="ACT">ACT</option>
                            <option value="NT">NT</option>
                        </select>
                        <input id="txtPostCode" class="easyui-validatebox" style="width: 92px;" />
                    </div>
                    <br />

                    <div class="fitem">
                        <label style="width: auto; margin-left: 10px;">Update Data to Client Profile :</label>
                        <input id="chkClientProfile" type="checkbox" checked="checked" />
                    </div>
                    <br />
                    <div class="fitem">
                        <label class="lable_left">BANK :</label>
                    </div>
                    <div class="fitem">
                        <label class="lable_left">Bank Name:</label>
                        <input id="txtBank" class="easyui-validatebox" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label class="lable_left">BSB :</label>
                        <input id="txtbsb" class="easyui-validatebox" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label class="lable_left">Account Name:</label>
                        <input id="txtAccName" class="easyui-validatebox" style="width: 120px" />
                    </div>
                    <div class="fitem">
                        <label class="lable_left">Account No:</label>
                        <input id="txtAccNo" class="easyui-validatebox" style="width: 120px" />
                    </div>
                    <br />
                    <br />
                    <br />
                    <div class="fitem" style="float: left">
                        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-save" onclick="saveContractAsDraft()">Save Draft </a>
                        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" onclick="generateContract()">Generate Contract </a>
                    </div>
                </div>

            </div>

            <div class="easyui-dialog" id="dlgPaymnetSchedule" title="Payment Schedule" style="width: 400px; height: 380px; padding: 5px;" closed="true">
                <table id="dgSchedule" style="width: auto; height: 330px" autorowheight="true" rownumbers="true" fitcolumns="true" singleselect="true">
                    <thead>
                        <tr>
                            <th field="DueDate" data-options="formatter:formatLoanDate" width="60">Due Date</th>
                            <th field="Repayment" data-options="formatter:ReplaceNumberWithCommas" width="60">Repayment</th>
                            <th field="Feecharge" data-options="formatter:ReplaceNumberWithCommas" width="60">Feecharge</th>
                            <th field="Balance" data-options="formatter:ReplaceNumberWithCommas" width="60">Balance </th>
                        </tr>
                    </thead>
                </table>

            </div>

        </div>
    </form>

    <script type="text/javascript">
        var form_change = false;

        window.onbeforeunload = function (e) {
            if (form_change == true)
                e.preventDefault();
        }

        function confirm() {
            if (form_change == true) {
                $.messager.confirm('Morgan CRM', 'Are you sure to close without saving ?', function (r) {
                    if (r) {
                        window.onbeforeunload = null;
                        window.close();
                    }
                });
            }
            else {
                window.onbeforeunload = null;
                window.close();
            }
        }

        $(document).ready(function () {
            bindDataForContract();
            bindOnblurForDateboxController();
            $('#pnlMain').panel('resize', {
                width: window.innerWidth - 2,
                height: window.innerHeight - 2
            });
            $(".numeric").numeric();
            $('.equal_div').on('change', 'input:text', function () {
                form_change = true;
            });
            $('#txtDateBirth').datebox({
                onSelect: function (date) {
                    form_change = true;

                }
            });

            $('#txtFirstPaymentDate').datebox({
                onSelect: function (date) {
                    form_change = true;
                }
            });
            $('#txtSettleDate').datebox({
                onSelect: function (date) {
                    form_change = true;
                }
            });
            $('#cmbState').combobox({
                onSelect: function (date) {
                    form_change = true;
                }
            });

        });
        window.onresize = function () {
            $('#pnlMain').panel('resize', {
                width: window.innerWidth - 2,
                height: window.innerHeight - 2
            });
        }
        function bindOnblurForDateboxController() {
            var txtSettleDate = $('#txtSettleDate').datebox('textbox');
            var txtFirstPaymentDate = $('#txtFirstPaymentDate').datebox('textbox');

            txtSettleDate.bind('blur', function () {
                CheckPaymentTermsByMonth();
            });

            txtFirstPaymentDate.bind('blur', function () {
                CheckPaymentTermsByMonth();
            });

        }
        function getQuerystring(key, defaultValue) {
            if (defaultValue == null) defaultValue = "";
            key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
            var qs = regex.exec(window.location.href);
            if (qs == null)
                return defaultValue;
            else {
                return qs[1];
            }
        }
        function ReplaceNumberWithCommas(yourNumber) {
            if (yourNumber != null) {
                //Seperates the components of the number
                var components = yourNumber.toString().split(".");
                //Comma-fies the first part
                components[0] = components[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                //Combines the two sections
                return "$" + components.join(".");
            }
        }
        jQuery(function ($) {
            $('#txtPostCode').mask("9999");
        });
        function changePrice(id) {
            $('#' + id).formatCurrency();
        }
        function DateInDBFormat(value) {
            dArr = value.split('/');
            return dArr[2] + '-' + dArr[1] + '-' + dArr[0];
        }
        function generateContract() {
            form_change = false;
            window.onbeforeunload = null;
            var v_loanAmount = $('#txtLoanAmount').val().replace(/,/g, '').replace('$', '');
            var v_establishFee = $('#txtEstablishFee').val();
            var v_MontlyFee = $('#txtMontlyFee').val();
            var v_SettleDate = $('#txtSettleDate').datebox('getValue');
            v_SettleDate = DateInDBFormat(v_SettleDate);
            var v_FirstPaymentDate = $('#txtFirstPaymentDate').datebox('getValue');
            v_FirstPaymentDate = DateInDBFormat(v_FirstPaymentDate);
            var v_dateBirth = $('#txtDateBirth').datebox('getValue');
            v_dateBirth = DateInDBFormat(v_dateBirth);

            var v_LastPaymentDate = DateInDBFormat($('#txtLastPaymentDate').val());
            var v_RepaymentBy = $('#cmbRepaymentBy').val();

            var v_Repayment = $('#txtRepayment').val().replace(/,/g, '').replace('$', '');;
            var v_totalEstFee = $('#txtTotalEstablishFee').val().replace(/,/g, '').replace('$', '');;
            var v_TotalMonthlyFee = $('#txtTotalMonthlyFee').val().replace(/,/g, '').replace('$', '');;
            var v_term = $('#txtTerm').numberbox('getValue');
            var flag = 0;

            if (document.getElementById("chkClientProfile").checked == true)
                flag = 1;

            var hOperator = $('#hdnUserName').val();

            $.ajax({
                url: '/WebServices/AM/ApplicationContract.ashx?method=generateContract',
                data: {
                    app_id: getQuerystring('app_id', ''),
                    ContactID: $('#hdnContactID').val(),
                    LoanAmount: v_loanAmount,
                    EstablishFee: v_establishFee,
                    MonthlyFee: v_MontlyFee,
                    SettleDate: v_SettleDate,
                    firstPaymentDate: v_FirstPaymentDate,
                    LastPaymentDate: v_LastPaymentDate,
                    RepaymentBy: v_RepaymentBy,
                    Term: v_term,
                    TermbyMonth: $('#lblTermByMonth').val(),

                    repaymentAmt: v_Repayment,
                    totalEstFee: v_totalEstFee,
                    totalmonthFee: v_TotalMonthlyFee,

                    BankName: $('#txtBank').val(),
                    BSB: $('#txtbsb').val(),
                    AccName: $('#txtAccName').val(),
                    AccNo: $('#txtAccNo').val(),
                    FirstName: $('#txtFirstName').val(),
                    MiddleName: $('#txtMiddleName').val(),
                    LastName: $('#txtLastName').val(),
                    DateBirth: v_dateBirth,
                    DriverLicense: $('#txtDriverLicense').val(),
                    StreetNo: $('#txtStreetNo').val(),
                    Street: $('#txtStreet').val(),
                    Suburb: $('#txtSuburb').val(),
                    State: $('#cmbState').combobox('getValue'),
                    PostCode: $('#txtPostCode').val().replace(/_/gi, ""),
                    historyOperator: hOperator,
                    updateClientProfile: flag,
                    filePath: $('#hdnFilePath').val()
                },
                success: function (response) {
                    var rec = response.split('#');
                    $('hdnLoanContractID').val(rec[0]);
                    $('#hdnFilePath').val(rec[1]);
                    window.opener.location.reload(true);
                    window.open('/Pages/Application/MCData/Contract/' + $('#hdnFilePath').val(), '_blank');
                    window.close();
                }
            });
        }

        function saveContractAsDraft() {
            form_change = false;
            window.onbeforeunload = null;
            var v_loanAmount = $('#txtLoanAmount').val().replace(/,/g, '').replace('$', '');

            var v_establishFee = $('#txtEstablishFee').val();
            var v_MontlyFee = $('#txtMontlyFee').val();
            var v_SettleDate = $('#txtSettleDate').datebox('getValue');
            v_SettleDate = DateInDBFormat(v_SettleDate);
            var v_FirstPaymentDate = $('#txtFirstPaymentDate').datebox('getValue');
            v_FirstPaymentDate = DateInDBFormat(v_FirstPaymentDate);

            var v_LastPaymentDate = DateInDBFormat($('#txtLastPaymentDate').val());

            var v_dateBirth = $('#txtDateBirth').datebox('getValue');
            v_dateBirth = DateInDBFormat(v_dateBirth);
            var v_RepaymentBy = $('#cmbRepaymentBy').val();
            var v_term = $('#txtTerm').numberbox('getValue');
            var flag = 0;

            if (document.getElementById("chkClientProfile").checked == true)
                flag = 1;

            var hOperator = $('#hdnUserName').val();

            $.ajax({
                url: '/WebServices/AM/ApplicationContract.ashx?method=saveContractDraft',
                data: {
                    app_id: getQuerystring('app_id', ''),
                    ContactID: $('#hdnContactID').val(),
                    LoanAmount: v_loanAmount,
                    EstablishFee: v_establishFee,
                    MonthlyFee: v_MontlyFee,
                    SettleDate: v_SettleDate,
                    firstPaymentDate: v_FirstPaymentDate,
                    LastPaymentDate: v_LastPaymentDate,
                    RepaymentBy: v_RepaymentBy,
                    Term: v_term,
                    TermbyMonth: $('#lblTermByMonth').val(),
                    BankName: $('#txtBank').val(),
                    BSB: $('#txtbsb').val(),
                    AccName: $('#txtAccName').val(),
                    AccNo: $('#txtAccNo').val(),
                    FirstName: $('#txtFirstName').val(),
                    MiddleName: $('#txtMiddleName').val(),
                    LastName: $('#txtLastName').val(),
                    DateBirth: v_dateBirth,
                    DriverLicense: $('#txtDriverLicense').val(),
                    StreetNo: $('#txtStreetNo').val(),
                    Street: $('#txtStreet').val(),
                    Suburb: $('#txtSuburb').val(),
                    State: $('#cmbState').combobox('getValue'),
                    PostCode: $('#txtPostCode').val().replace(/_/gi, ""),
                    updateClientProfile: flag,
                    historyOperator: hOperator,
                    filePath: $('#hdnFilePath').val()
                },
                success: function (response) {

                    if (response == 'True') {
                        window.close();
                    }
                    else
                        $.messager.alert('Morgan CRM', 'Error While saving Contract Draft');
                }
            });
        }


        function bindDataForContract() {
            $.ajax({
                url: '/WebServices/AM/ApplicationContract.ashx?method=getDataForApplicationContract',
                data: { appid: getQuerystring('app_id', '') },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        $('#lblmsg').html('');

                        if (rec.DefaultData == "1") {
                            // DefaultData
                            $('#hdnContactID').val(rec.ContactID);
                            $('#txtFirstName').val(rec.FirstName);
                            $('#txtMiddleName').val(rec.MiddleName);
                            $('#txtLastName').val(rec.SurName);
                            $('#txtDateBirth').datebox('setValue', au_formatter(rec.DateBirth, null));
                            $('#txtDriverLicense').val(rec.DriverLicense);
                            $('#txtStreet').val(rec.Street);
                            $('#txtStreetNo').val(rec.StreetNo);
                            $('#txtSuburb').val(rec.Suburb);
                            $('#cmbState').combobox('setValue', rec.State);
                            if (rec.PostCode.indexOf('_') < 0) {
                                $('#txtPostCode').val(rec.PostCode);
                            }

                            //var loanAmount = rec.DesiredAmount;
                            //if (loanAmount > 1000) {
                            //    loanAmount = 1000;
                            //}
                            var loanTerm = Math.round(rec.mc_preferred_loan_period * 4);
                            $('#txtTerm').numberbox('setValue', loanTerm);
                            var loanAmount = rec.OfferedAmount;
                            $('#txtLoanAmount').val(loanAmount).formatCurrency();
                            $('#txtEstablishFee').val(rec.EstablishFee);
                            $('#txtMontlyFee').val(rec.MonthlyFee);
                            $('#txtSettleDate').datebox('setValue', formatLoanDate(rec.SettleDate));
                            $('#txtFirstPaymentDate').datebox('setValue', formatLoanDate(rec.firstpaymentDate));
                            $('#cmbRepaymentBy').val('7');

                            //$('#txtTerm').val(26);                           
                            Calculate_payment();
                        }
                        else {

                            $('#txtLoanAmount').val(rec.LoanAmount).formatCurrency();
                            $('#txtEstablishFee').val(rec.EstablishFee);
                            $('#txtMontlyFee').val(rec.MonthlyFee);
                            $('#txtSettleDate').datebox('setValue', formatLoanDate(rec.SettleDate));
                            $('#txtFirstPaymentDate').datebox('setValue', formatLoanDate(rec.firstPaymentDate));
                            $('#cmbRepaymentBy').val(rec.RepaymentBy);
                            $('#txtTerm').numberbox('setValue', rec.Term);
                            $('#txtBank').val(rec.BankName);
                            $('#txtbsb').val(rec.BSB);
                            // $('#txtLoanCreateDate').html(formatLoanDate(rec.CreatedDate));
                            $('#txtFirstName').val(rec.FirstName);
                            $('#txtMiddleName').val(rec.MiddleName);
                            $('#txtLastName').val(rec.LastName);
                            $('#txtDateBirth').datebox('setValue', au_formatter(rec.DateBirth, null));
                            $('#txtDriverLicense').val(rec.DriverLicense);
                            $('#txtStreet').val(rec.Street);
                            $('#txtStreetNo').val(rec.StreetNo);
                            $('#txtSuburb').val(rec.Suburb);
                            $('#cmbState').combobox('setValue', rec.State);
                            if (rec.PostCode.indexOf('_') < 0) {
                                $('#txtPostCode').val(rec.PostCode);
                            }
                            $('#txtAccNo').val(rec.AccountNo);
                            $('#txtAccName').val(rec.AccountName);
                            $('#hdnContactID').val(rec.ContactID);
                            $('#hdnFilePath').val(rec.FilePath);
                            $('#txtContractCreateDate').html(rec.DraftDate);
                            Calculate_payment();
                        }

                    });
                }
            });
        }

        function PrepareSchedule() {
            var v_loanAmount = $('#txtLoanAmount').val().replace(/,/g, '').replace('$', '');
            var v_establishFee = $('#txtEstablishFee').val();
            var v_MontlyFee = $('#txtMontlyFee').val();
            var v_SettleDate = $('#txtSettleDate').datebox('getValue');
            var v_FirstPaymentDate = $('#txtFirstPaymentDate').datebox('getValue');
            var v_RepaymentBy = $('#cmbRepaymentBy').val();
            var v_term = $('#txtTerm').numberbox('getValue');
            $('#dgSchedule').datagrid({
                url: '/WebServices/AM/ApplicationContract.ashx?method=PrepareSchedule&loanAmount=' + v_loanAmount + '&establishFee=' + v_establishFee + '&monthlyFee=' + v_MontlyFee +
                    '&settleDate=' + v_SettleDate + '&paymentDate=' + v_FirstPaymentDate + '&repaymentBy=' + v_RepaymentBy + '&term=' + v_term
            });
            $('#dlgPaymnetSchedule').dialog('open');
            $('#dlgPaymnetSchedule').dialog('center');
        }
        function au_formatter(value, row) {
            var date = (value === null) ? new Date() : new Date(value);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var d = date.getDate();
            return (d < 10 ? ('0' + d) : d) + '/' + (m < 10 ? ('0' + m) : m) + '/' + y;
        }
        function au_parser(s) {
            if (!s) return new Date();
            var ss = (s.split('/'));
            var d = new Number(ss[0]);
            var m = new Number(ss[1]);
            var y = new Number(ss[2]);
            var currentDate;
            if (!isNaN(d) && !isNaN(m) && !isNaN(y)) {

                return new Date(y, m - 1, d);
            }
            else {
                return new Date();
            }
        }
        function formatLoanDate(value, row) {
            if (value == null)
                return value;
            var date = new Date(value);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var d = date.getDate();
            return (d < 10 ? ('0' + d) : d) + '/' + (m < 10 ? ('0' + m) : m) + '/' + y;
        }
        function Convert_To_DefaultDate(value) {
            dArr = value.split('/');
            return dArr[1] + '/' + dArr[0] + '/' + dArr[2];
        }

        function IsValidLoanAmount() {
            var loanAmount = $('#txtLoanAmount').val().replace(/,/g, '').replace('$', '');

            if (loanAmount > 2000)
                $('#lblmsg').html('Maximum loan amount should be less than or equal <span style="color:red;font-weight:bold">' + 2000 + '</span> . \n');
            else if (loanAmount < 100)
                $('#lblmsg').html('Minimum loan amount should be great than <span style="color:red;font-weight:bold">' + 100 + '</span> . \n');
            else
                $('#lblmsg').html('');
        }
        function IsContractDatePassValidation() {
            var invalidDateMessage = '';
            var settleDate = GetDateById('txtSettleDate');
            var firstPaymentDate = GetDateById('txtFirstPaymentDate');
            var repaymentBy = $('#cmbRepaymentBy').val();
            var term = $('#txtTerm').numberbox('getValue');
            var isPassed = false;
            var establishFee = $('#txtEstablishFee').val();
            var montlyFee = $('#txtMontlyFee').val();

            //var loanAmount = $('#txtLoanAmount').val().replace(/,/g, '').replace('$', '');
            //if (loanAmount > 2000) {
            //    invalidDateMessage += 'Maximum loan amount should be less than or equal <span style="color:red;font-weight:bold">' + 2000 + '</span> . \n';
            //}
            //if (loanAmount < 100) {
            //    invalidDateMessage += 'Minimum loan amount should be great than <span style="color:red;font-weight:bold">' + 100 + '</span> . \n';
            //}
            if (term < 1) {
                invalidDateMessage += 'Term can not be zero';
            }

            if (!IsValidDate('txtSettleDate')) {
                invalidDateMessage += 'Settle Date: <span style="color:red;font-weight:bold">' + $('#txtSettleDate').datebox('getValue') + '</span> is not valid date. \n';
            }

            if (!IsValidDate('txtFirstPaymentDate')) {
                invalidDateMessage += '\nFirst Payment Date: <span style="color:red;font-weight:bold">' + $('#txtFirstPaymentDate').datebox('getValue') + '</span> is not valid date. \n';
            }

            if (invalidDateMessage.length == 0) {

                if (IsPaymentDateLessThanSettleDate(firstPaymentDate, settleDate)) {
                    invalidDateMessage = 'First Payment date can not be less than settle date';
                }
                else if (IsFirstPaymentDateOverContractDueDate(settleDate, firstPaymentDate, term)) {
                    invalidDateMessage = 'First Payment date is over contract due date';
                }
                else {
                    isPassed = true;
                    CheckPaymentTermsByMonth();
                    var termByMonth = $('#lblTermByMonth').val();
                    if ($('#cmbRepaymentBy').val() == "30") {
                        var dayOfFirstPayment = firstPaymentDate.getDate();
                        if (dayOfFirstPayment > 28) {
                            if (!IsSameDayExistInFollowingMonth(firstPaymentDate, termByMonth)) {
                                invalidDateMessage = 'Day ' + dayOfFirstPayment + ' is not exist in the following payment due date.';
                                isPassed = false;
                            }
                        }
                    }
                }
            }

            if (invalidDateMessage) {
                $('#lblmsg').html(invalidDateMessage);
                //$.messager.alert('Morgan CRM', invalidDateMessage);
            }
            return isPassed;
        }


        function Calculate_payment() {

            if (IsContractDatePassValidation()) {
                $('#txtLastPayment').val('0');
                $('#btnSchedule').linkbutton('enable');
                var v_loanAmount = $('#txtLoanAmount').val().replace(/,/g, '').replace('$', '');

                if (v_loanAmount == '0' || v_loanAmount == '') {
                    $('#lblmsg').html('Loan Amount Can not be Zero or Empty');
                    return;
                }
                var v_establishFee = $('#txtEstablishFee').val();
                var v_MontlyFee = $('#txtMontlyFee').val();
                var v_SettleDate = $('#txtSettleDate').datebox('getValue');

                var v_FirstPaymentDate = $('#txtFirstPaymentDate').datebox('getValue');
                var v_RepaymentBy = $('#cmbRepaymentBy').val();
                var v_term = $('#txtTerm').numberbox('getValue');

                $.ajax({
                    url: '/WebServices/AM/ApplicationContract.ashx?method=calculateByTerm',
                    data: {
                        loanAmount: v_loanAmount, establishFee: v_establishFee, monthlyFee: v_MontlyFee, settleDate: v_SettleDate,
                        paymentDate: v_FirstPaymentDate, repaymentBy: v_RepaymentBy, term: v_term
                    },
                    success: function (data) {
                        var data_array = data.split('#');
                        $('#txtRepayment').val(data_array[0]).formatCurrency();
                        $('#txtTotalEstablishFee').val(data_array[1]).formatCurrency();
                        $('#txtTotalMonthlyFee').val(data_array[2]).formatCurrency();
                        $('#txtTotalFee').val(data_array[3]).formatCurrency();
                        $('#txtLastPaymentDate').val(data_array[4]);
                    }
                });
            }
            else {
                InvalidDateHandler();
            }
        }

        function InvalidDateHandler() {
            $('#btnSchedule').linkbutton('disable');
            $('#txtRepayment').val('0');
            $('#txtTotalEstablishFee').val('0');
            $('#txtTotalMonthlyFee').val('0');
            $('#txtTotalFee').val('0');
            $('#txtLastPaymentDate').val('0');
        }

        function GetDateById(id) {
            var currentDate = $('#' + id).datebox('getValue').split('/');
            var d = new Number(currentDate[0]);
            var m = new Number(currentDate[1]);
            var y = new Number(currentDate[2]);
            return new Date(y, m - 1, d);
        }

        function IsValidDate(id) {
            var isValid = false;
            var currentDate = $('#' + id).datebox('getValue').split('/');
            var d = new Number(currentDate[0]);
            var m = new Number(currentDate[1]);
            var y = new Number(currentDate[2]);
            var matchedDate = new Date(y, m - 1, d);

            if (matchedDate.getFullYear() == y && matchedDate.getMonth() + 1 == m && matchedDate.getDate() == d) {
                isValid = true;
            }
            return isValid;
        }

        function IsPaymentDateLessThanSettleDate(firstPaymentDate, settleDate) {
            return firstPaymentDate < settleDate;
        }
        function CheckPaymentTermsByMonth() {
            InvalidDateHandler();
            var settleDate = $('#txtSettleDate').datebox('getValue');
            // settleDate = Convert_To_DefaultDate(settleDate);

            var firstPaymentDate = $('#txtFirstPaymentDate').datebox('getValue');
            // firstPaymentDate = Convert_To_DefaultDate(firstPaymentDate);
            var term = $('#txtTerm').numberbox('getValue');
            var repaymentBy = $('#cmbRepaymentBy').val();
            $.ajax({
                url: '/WebServices/AM/ApplicationContract.ashx?method=GetPaymentTermsByMonth',
                data: { settleDate: settleDate, paymentDate: firstPaymentDate, term: term, repaymentBy: repaymentBy },
                success: function (data) {
                    $('#lblTermByMonth').val(data);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("error");
                }
            });
        }

        function IsFirstPaymentDateOverContractDueDate(settleDate, firstPaymentDate, loanTerm) {
            var contractDueDate = new Date(settleDate.getTime() + loanTerm * 7 * 24 * 60 * 60 * 1000);
            return firstPaymentDate > contractDueDate;
        }
        function IsSameDayExistInFollowingMonth(paymentDate, termByMonth) {
            var day = paymentDate.getDate();
            var year = paymentDate.getFullYear();
            var month = paymentDate.getMonth();
            var nextPaymentDate = null;
            var lastDayOfMonth = 0;
            var nextmonth = 0;
            var currentYear = year;
            var isSameDayFound = true;

            for (var i = 1; i < termByMonth; i++) {

                nextmonth = month + i;

                if (nextmonth > 11) {
                    currentYear = year + 1;
                    nextmonth = nextmonth - 12;
                }

                lastDayOfMonth = new Date(currentYear, nextmonth + 1, 0);

                if (day > lastDayOfMonth.getDate()) {
                    isSameDayFound = false;
                    break;
                }
            }
            return isSameDayFound;
        }
    </script>
</body>
</html>
